"""
该模块主要用于1d,2d,3d的plot函数
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mtplb
from .plot_parm import *
from mpl_toolkits.mplot3d import Axes3D
from analyse.tool.code_help import dprint


def sdf_plot():
    return 0


def plot_1d(
    xslice,
    var,
    ax,
    pp=None,
    vmax=None,
    min=None,
    unit=1,
    xunit=1,
    title='',
    label='test',
    color='b',
):
    """
    arg:
    可选参数ifsdf默认为真--便捷sdf数据画图；ifsdf=0时常规画图;当前默认为1
    @xslice ifsdf=1:x方向的数据切片; ifsdf=0:x方向数据列表
    @var(相应的sdf类型的数据如Electric_Field_Ey),ax(当前需要绘图的axis对象),
        如果是ifsdf为真(默认)，
    @==================================
    @可选参数-绘图相应的各种细节控制，默认值请在plot_parm.py文件中修改。
    @unit:所画强度量的归一化(y轴)--pp中有常用的参数
    """
    if (pp != None):
        unit = pp.unit
        title = pp.title
        X = var.grid_mid.data[0][xslice]
        X = X / pp.xunit
        tempax = ax.plot(X, var.data[xslice] / unit, label=label, color=color)
        ax.set_xlabel(pp.xlabel)
        ax.set_ylabel(pp.Elabel)
        ax.set_title('%s' % (title))
        return tempax
    else:
        #未定义para参数时进入一般的画图函数
        tempax = ax.plot(xslice / xunit, var / unit, label=label, color=color)
        ax.set_xlabel('x-axis')
        ax.set_ylabel('y-axis')
        ax.set_title('no-para')
        return tempax


def plot_2d(xslice,
            yslice,
            var,
            ax,
            pp=None,
            method='pcolormesh',
            vmax=None,
            vmin=None,
            shading=None,
            cmap=None,
            title='',
            norm=None,
            levels=10,
            unit=1,
            aspect='auto'):
    """
    可选参数ifsdf默认为真--便捷sdf数据画图；ifsdf=0时常规画图;当前默认为1
    @xslice ifsdf=1:x方向的数据切片; ifsdf=0:x方向数据列表
    @yslice ifsdf=1:y方向的数据切片; ifsdf=0:y方向数据列表
    @var(相应的sdf类型的数据如Electric_Field_Ey),ax(当前需要绘图的axis对象),
        如果是ifsdf为真(默认)，
    @可选参数-绘图相应的各种细节控制，默认值请在plot_parm.py文件中修改。
    
    """
    if (pp != None):
        method = pp.method
        unit = pp.unit
        vmax = pp.vmax / unit
        vmin = pp.vmin / unit
        deltav = (vmax - vmin) / pp.levels
        levels = np.arange(vmin, vmax, deltav)
        norm = mtplb.colors.Normalize(vmin=vmin, vmax=vmax)
        X, Y = np.meshgrid(var.grid_mid.data[0][xslice] / pp.xunit,
                           var.grid_mid.data[1][yslice] / pp.yunit)
        shading = pp.shading
        cmap = pp.cmap
        aspect = pp.aspect
        title = pp.title
        ax.set_title('%s' % (title))
        if method == 'pcolormesh':
            parm = 'X,Y,var.data.T[yslice, xslice]/unit,\
                    cmap=cmap,norm=norm,shading=shading'

        elif method == 'plot_surface':
            parm = 'X,Y,var.data.T[yslice, xslice]/unit,\
                    cmap=cmap,norm=norm'

        elif method == 'imshow':
            parm = 'var.data.T[yslice, xslice]/unit,\
                    cmap=cmap,\
                    aspect=aspect'

        else:
            print('未找到对应的绘图函数')
        # elif method == 'imshow':
        #     parm = 'var.data.T[yslice, xslice]'
        dprint('运行的命令未：', method, '(', parm, ')')
        dprint('参数为：', ' vmax:', vmax, ' vmin:', vmin, ' unit:', unit, '\n',
               ' aspect:', aspect, ' shading:', shading)
        tempfunc = 'getattr(ax, method)(' + parm + ')'
        tempax = eval(tempfunc)
        ax.set_xlabel(pp.xlabel)
        ax.set_ylabel(pp.ylabel)
        # tempax = ax[method](X,Y,var.data.T[yslice, xslice],vmin=pp.vmin,vmax=pp.vmax,cmap=pp.cmap,norm=pp.norm,shading=pp.shading)
    elif (pp == None):
        if ((vmax != None) and (vmin != None)):
            vmax = vmax / unit
            vmin = vmin / unit
            deltav = vmax / levels
            levels = np.arange(vmin, vmax, deltav)
            norm = mtplb.colors.Normalize(vmin=vmin, vmax=vmax)
            ax.set_title('%s' % (title))
            xslice, yslice = np.meshgrid(xslice, yslice)
        if method == 'pcolormesh':
            parm = 'xslice, yslice,var.T/unit,'\
                +'cmap=cmap,norm=norm,shading=shading'

        elif method == 'imshow':
            parm = 'var.data.T[yslice, xslice]/unit,\
                    cmap=cmap,\
                    aspect=aspect'

        tempfunc = 'getattr(ax, method)(' + parm + ')'
        tempax = eval(tempfunc)
        dprint('运行的命令未：', method, '(', parm, ')')
        dprint('参数为：', ' vmax:', vmax, ' vmin:', vmin, ' unit:', unit, '\n',
               ' aspect:', aspect, ' shading:', shading)
        ax.set_xlabel('x-axis')
        ax.set_ylabel('y-axis')
        # tempax = getattr(ax, method)(eval(parm))
        # tempax = ax.pcolormesh(xslice,
        #                        yslice,
        #                        var,
        #                        vmin=pp.vmin,
        #                        vmax=pp.vmax,
        #                        cmap=pp.cmap,
        #                        norm=pp.norm,
        #                        shading=pp.shading)
    return tempax


def plot_3d(var,
            xslice,
            yslice,
            ax,
            pp=None,
            vmax=None,
            min=None,
            levels=10,
            norm=None,
            shading=None,
            cmap=None,
            title=''):
    """
    @var(相应的sdf类型的数据,如Electric_Field_Ey),xslice,yslice,ax(当前需要绘图的axis对象),
    当前默认是分析x，y截面的数据
    绘图相应的各种细节控制，引用plot_parm模块中定义的数据
    """
    if (pp != None):
        X, Y = np.meshgrid(var.grid_mid.data[0][xslice],
                           var.grid_mid.data[1][yslice])
        ax.set_title('file_x_y_profile_%s' % (pp.title))
        ax.pcolormesh(X,
                      Y,
                      var.data.T[int(len(var.data[0, 0, :]) / 2), yslice,
                                 xslice],
                      vmin=pp.vmin,
                      vmax=pp.vmax,
                      cmap=pp.cmap,
                      norm=pp.norm,
                      shading=pp.shading)
        return 0


def share_colorbar(fig, tempax):
    #前面三个子图的总宽度 为 全部宽度的 0.9；剩下的0.1用来放置colorbar
    fig.subplots_adjust(right=0.9)
    #colorbar 左 下 宽 高
    l = 0.92
    b = 0.12
    w = 0.015
    h = 1 - 2 * b

    #对应 l,b,w,h；设置colorbar位置；
    rect = [l, b, w, h]
    cbar_ax = fig.add_axes(rect)
    cb = plt.colorbar(tempax, cax=cbar_ax)
    return cb